//
//  JsRequestBuilderB.m
//  JsUtilitySdk
//
//  Created by Gikki Ares on 2023/4/10.
//


/**
 采用 NSURLSession实现.
 */
#import "JsRequestBuilderB.h"
#import "JsRequestUtil.h"
#import "JsYy_Model.h"

@interface JsRequestBuilderB()<NSURLSessionDelegate> {
//	NSURLSession * mUrlSession;
}
@end

@implementation JsRequestBuilderB

+(instancetype)sharedInstance {
	static JsRequestBuilderB * _sharedInstance;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		_sharedInstance = [[JsRequestBuilderB alloc]init];
	});
	return _sharedInstance;
}

- (instancetype)init {
	if(self = [super init]) {
		
	}
	return self;
}




- (NSURLSessionDataTask *)invokeDataTaskWithConfig:(JsRequestConfig *)config info:(JsRequestInfo *)info completionHandler:(JsResponseHandler)handler {
	NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:config.requestUrlString]];
	//请求方式
	[request setHTTPMethod:[config requestMethodName]];
	//请求体
	{
		if(config.requestBodyInput) {
			NSData * requestBodyData = nil;
			switch(config.requestBodyInputType){
				case JsRequestBodyInputTypeData:{
					requestBodyData = config.requestBodyInput;
					break;
				}
				case JsRequestBodyInputTypeMapToJson:{
					//json格式数据,需要设置Content-Type:application/json
					[config setValue:@"application/json" forRequestHeaderKey:@"Content-Type"];
					requestBodyData = [config.requestBodyInput jsyy_modelToJSONData];
					break;
				}
				default:{
					//TODO: 其他方式需要补充.
				}
			}
			request.HTTPBody = requestBodyData;
				//如果有请求体,需要添加请求头 Content-Length
		}
	}
	{
		//请求头
		if(config.requestHeader) {
			[config.requestHeader enumerateKeysAndObjectsUsingBlock:^(NSString *  _Nonnull key, NSString *  _Nonnull obj, BOOL * _Nonnull stop) {
				[request setValue:obj forHTTPHeaderField:key];
			}];
		}
	}
//	[NSURLSession sharedSession]
	NSURLSession * session = [self sessionFromConfig:config];
	
	info.requestHeader = request.allHTTPHeaderFields;
	NSArray * cookieArray = session.configuration.HTTPCookieStorage.cookies;
	info.cookies = cookieArray;
	NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
		[JsRequestUtil handleResponseObject:data response:(NSHTTPURLResponse *)response error:error config:config info:info completion:handler];
	}];
	if (@available(iOS 15.0, *)) {
		task.delegate = self;
	} else {
			// Fallback on earlier versions
	}
	[task resume];
	return task;
}

- (NSArray *)currentCookieArray {
	return nil;
}

#pragma mark 3 Inner Func
- (NSURLSession *)sessionFromConfig:(JsRequestConfig *)config {
	NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
	
		//NSURLRequestReloadIgnoringLocalCacheData,比如请求2次一样的url,会直接返回第一次请求的结果.
	configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
	configuration.timeoutIntervalForRequest = config.timeout.floatValue;
	NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration];
	return session;
}

#pragma mark 4 Delegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
	NSLog(@"didReceiveChallenge:%@",challenge.error.userInfo);
		//直接信任.
	NSURLCredential * credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
	NSURLSessionAuthChallengeDisposition  disposition = NSURLSessionAuthChallengeUseCredential;
	completionHandler(disposition,credential);
}

@end
